package com.example.batterynotification;

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class SeekbarPreferenceClass extends Preference {

	enum Elevel {
		HIGHLEVEL, LOWLEVEL
	};

	Elevel elevel;

	public SeekbarPreferenceClass(Context context, AttributeSet attrs) {
		super(context, attrs);
		TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
				R.styleable.CustomSwitch, 0, 0);


		if(context.toString().contains("com.example.batterynotification.HighLevelSettingActivity"))
		{
			elevel = Elevel.HIGHLEVEL;
		}
		else
		{
			elevel = Elevel.LOWLEVEL;
		}		
	}

	@Override
	protected View onCreateView(ViewGroup parent) {

		LayoutInflater li = (LayoutInflater) getContext().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE);
		View view = li.inflate(R.layout.seek_bar_pref, parent, false);

		final TextView SeekBarLevelTxt = (TextView) view
				.findViewById(R.id.seekBarLevel);

		final CustomSeekBar seekBar = (CustomSeekBar) view
				.findViewById(R.id.seekbar);
		int progress = 0;
		if (elevel == Elevel.HIGHLEVEL)
		{
			seekBar.setMaxLevel(100);
			seekBar.setMinLevel(51);
			progress = Preferences.getIntPreferences("prefHighBatteryLevel");
			if (progress == -1)
				seekBar.setCurrentLevel(51);
		}
		else 
		{
			seekBar.setMaxLevel(50);
			seekBar.setMinLevel(1);
			progress = Preferences.getIntPreferences("prefLowBatteryLevel");
			if (progress == -1)
				seekBar.setCurrentLevel(0);
		}

		seekBar.setCurrentLevel(progress);
		SeekBarLevelTxt.setText(progress + " %");

		seekBar.setOnCustomSeekBarChangeListener(new OnCustomSeekBarChangeListener() {

			@Override
			public void onProgressChanged(int progress) {
				SeekBarLevelTxt.setText(seekBar.getCurrentLevel() + " %");
				if (elevel == Elevel.HIGHLEVEL) {
					if (seekBar.getCurrentLevel() <= 50)
						seekBar.setCurrentLevel(51);
					Preferences.savePreferences("prefHighBatteryLevel",
							seekBar.getCurrentLevel());
				} else {
					if (seekBar.getCurrentLevel() > 50)
						seekBar.setCurrentLevel(50);
					Preferences.savePreferences("prefLowBatteryLevel",
							seekBar.getCurrentLevel());
				}
			}
		});

		return view;
	}

}
